import {
  HostBinding,
  Component,
  OnInit,
  ViewChild,
  Input,
  Renderer2,
  forwardRef,
  Injector,
  Inject,
  DoCheck,
  ChangeDetectorRef
} from "@angular/core";
import {
  Observable,
  Subject,
  ReplaySubject,
  from,
  of,
  range,
  BehaviorSubject
} from "rxjs";
import { map, catchError, filter } from "rxjs/operators";
import { Router } from "@angular/router";
import {
  AsyncValidator,
  NG_ASYNC_VALIDATORS,
  ValidationErrors,
  AbstractControl,
  FormBuilder,
  FormGroup,
  Validators,
  ControlValueAccessor,
  NG_VALUE_ACCESSOR,
  FormControl
} from "@angular/forms";
import { Store, select } from "@ngrx/store";
import { Actions } from "@ngrx/effects";
import * as fromUser from "@/user/store/reducers/index";
import * as fromRoot from "@/reducers/index";
import { UserActions } from "@/user/store/actions";
import { ILoginRequest } from "@/user/store/models/user";
import { PLATFORM_ID, APP_ID } from "@angular/core";
import { isPlatformServer } from "@angular/common";
import { LocaleService, TranslationService, Language } from "angular-l10n";

import { ActivatedRoute } from "@angular/router";
import { EhAnimateService } from "@/share/services/eh-animate.service";
type IOnTab = "send" | "reset"; // 发送验证码 | 重置密码

@Component({
  selector: "app-forgot",
  templateUrl: "./forgot.component.html",
  styleUrls: ["./forgot.component.scss"],
  animations: [EhAnimateService.fadeInOut()]
})
export class ForgotComponent implements OnInit, DoCheck {
  @Language() lang: string;

  user$ = this.store.pipe(
    select(fromRoot.user),
    filter(user => !!user)
  );

  validateForm: FormGroup;
  validateForm2: FormGroup;

  hide = true;

  type = {
    email: "1",
    phone: "2"
  };

  timer;

  // 发送目标
  aim = "";

  @ViewChild("email")
  email;

  @ViewChild("sliderCodeRef")
  sliderCodeRef;

  isServer: boolean;

  onTab: IOnTab = "send";

  constructor(
    updates$: Actions,
    @Inject(PLATFORM_ID) private platformId: Object,
    private fb: FormBuilder,
    private renderer: Renderer2,
    private changeDetectorRef: ChangeDetectorRef,
    @Inject("StoreService") private storeService,
    @Inject("RegService") private regService,
    @Inject("UtilsService") private utilsService,
    @Inject("UserService") private userService,
    @Inject("MsgService") private msgService,
    private activatedRoute: ActivatedRoute,
    @Inject("HasUsernameValidatorService") private hasUsernameValidatorService,
    private router: Router,
    private store: Store<fromUser.State | fromRoot.State>
  ) {
    this.isServer = isPlatformServer(this.platformId);
  }

  req: ILoginRequest = {
    username: "",
    password: "",
    code: "",
    verify: {}
  };

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      username: new FormControl(null, {
        validators: [Validators.required],
        asyncValidators: [
          this.hasUsernameValidatorService.validate.bind(
            this.hasUsernameValidatorService
          )
        ],
        updateOn: "blur"
      }),
      code: new FormControl(null, {
        validators: [Validators.required],
        updateOn: "change"
      }),
      password: [null, [Validators.required]],
      password2: [null, [Validators.required, this.confirmationValidator]],
      verify: new FormControl(null, {
        validators: [Validators.required],
        updateOn: "change"
      })
    });

    this.addListen();
  }

  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls.password.value) {
      return { confirm: true, error: true };
    }
  };

  debounce(fn, time = 1000) {
    if (this.timer) {
      clearTimeout(this.timer);
    }
    this.timer = setTimeout(() => {
      fn();
      clearTimeout(this.timer);
    }, time);
  }

  ngDoCheck() {}

  addListen() {
    this.validateForm.valueChanges.subscribe(e => {
      this.req.username = e.username;
      this.req.password = e.password;
      this.req.code = e.code;
      this.req.verify = e.verify;
    });
  }

  // onNext() {
  //   this.router.navigate(["u/forgot2"], {
  //     queryParams: { req: JSON.stringify(this.req) }
  //   });
  // }

  onSubmit() {
    const savePwd = new UserActions.SavePwd({ req: this.req, cpt: this });
    this.store.dispatch(savePwd);
  }

  onChangeValidate(e) {
    this.validateForm.controls.verify.setValue(e);
    this.changeDetectorRef.detectChanges();
  }
}
